import './Sidebar.css'
import http from '@/utils/axios';
import { memo, useEffect, useState, useRef } from 'react';
import useStore from '@/store';
import { useNavigate } from 'react-router-dom';

import CircularProgress from '@mui/material/CircularProgress';

import MoreHorizOutlinedIcon from '@mui/icons-material/MoreHorizOutlined';
import MenuOpenOutlinedIcon from '@mui/icons-material/MenuOpenOutlined';
import PostAddOutlinedIcon from '@mui/icons-material/PostAddOutlined';
import TuneOutlinedIcon from '@mui/icons-material/TuneOutlined';
import { Flag } from '@mui/icons-material';

import RemoveOutlinedIcon from '@mui/icons-material/RemoveOutlined';


const DialogueHistoryTag = ({ item, containerRef }) => {
    const navigate = useNavigate();
    const isMobileView = useStore(state => state.isMobileView);
    const toggleSidebarVisibility = useStore(state => state.toggleSidebarVisibility);

    const currentDialogueUUID = useStore(state => state.currentDialogueUUID);
    const setCurrentDialogueUUID = useStore(state => state.setCurrentDialogueUUID);
    const deleteDialogueHistoryTag = useStore(state => state.deleteDialogueHistoryTag);
    const [isHovered, setIsHovered] = useState(false);
    const [isIconHovering, setIsIconHovering] = useState(false);
    const [isMoreMenuOpen, setIsMoreMenuOpen] = useState(false);
    const handleLoadMoreDialogueTags = useStore(state => state.handleLoadMoreDialogueTags);

    const isSelected = item.uuid == currentDialogueUUID;




    const onClickTag = (uuid) => {
        // navigate(`/c/${uuid}`)
        setCurrentDialogueUUID(uuid);
        if (isMobileView) toggleSidebarVisibility();

        if (currentDialogueUUID != uuid) {
            navigate(`/c/${uuid}`)
        }
    }

    const onClickOptionButton = async (uuid) => {
        // delete
        var userConfirmed = window.confirm("Are you sure?");
        if (!userConfirmed) return;

        try {
            await http.delete(`/dialogue/${uuid}`);
            await deleteDialogueHistoryTag(uuid)
            const { scrollHeight, clientHeight } = containerRef.current;
            // console.log(scrollHeight, clientHeight);
            if (scrollHeight == clientHeight) {
                handleLoadMoreDialogueTags();
            }
        } catch (error) {
            console.log(error.message);
        } finally {
            if (currentDialogueUUID === uuid) {
                navigate('/')
            }
        }
    }


    const titleInputRef = useRef(null);
    const [editingTitleValue, setEditingTitleValue] = useState('')
    const [isEditingTitle, setIsEditingTitle] = useState(false);
    const handleChangeTagTitle = useStore(state => state.handleChangeTagTitle);
    const onEditingTitleValueChange = (event) => {
        setEditingTitleValue(event.target.value);
    }
    const onDoubleClickTagTitle = () => {
        setIsEditingTitle(true);
    }
    const onEditingTitleBlur = () => {
        setIsEditingTitle(false)
        const pre_title = item.title || '';
        if (pre_title != editingTitleValue) {
            handleChangeTagTitle(item.uuid, editingTitleValue)
        }
    }
    useEffect(() => {
        if (isEditingTitle) {
            setEditingTitleValue(item.title || '')
            titleInputRef.current.focus();
        }
    }, [isEditingTitle])




    return (
        <div className='dialogue-history-tag'
            style={{ backgroundColor: isSelected ? '#303030' : '' }}

            onMouseMove={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
        >
            {isEditingTitle && <input type="text" value={editingTitleValue} onChange={onEditingTitleValueChange} onBlur={onEditingTitleBlur} ref={titleInputRef} />}
            {!isEditingTitle &&
                <>
                    <p onClick={() => onClickTag(item.uuid)} onDoubleClick={onDoubleClickTagTitle}>{item.title || 'Untitled'}</p>
                    <div style={{ position: 'relative', display: isHovered || isMobileView ? 'flex' : 'none', margin: '0px 8px', justifyContent: 'center', alignContent: 'center' }}>
                        <RemoveOutlinedIcon
                            style={{
                                color: isIconHovering ? '#d0d0d0' : '#a0a0a0',
                                cursor: 'pointer',
                            }}
                            fontSize='small'
                            onMouseMove={() => setIsIconHovering(true)}
                            onMouseLeave={() => setIsIconHovering(false)}
                            onClick={() => onClickOptionButton(item.uuid)} />
                        {/* <div className='dialogue-history-tag-more-menu'>123</div> */}
                    </div>
                </>
            }
            {/* <div className='dialogue-history-tag-more-menu' >

            </div> */}
        </div>
    )
}


const DialogueHistoryTags = ({ containerRef }) => {

    // console.log(currentDialogueUUID);
    // const [isLoading, setIsLoading] = useState(true);
    // const [error, setError] = useState(null);

    const isLoading = useStore(state => state.isDialogueTagsLoading);
    const error = useStore(state => state.dialogueTagsLoadingErrow);


    const dialogueHistoryTags = useStore(state => state.dialogueHistoryTags);
    const handleLoadMoreDialogueTags = useStore(state => state.handleLoadMoreDialogueTags);

    const handleScroll = () => {
        // console.log('handleScroll');
        // 获取容器和滚动条的相关信息
        const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
        // console.log(scrollTop, scrollHeight, clientHeight);
        // 判断是否滚动到达底部
        if (scrollTop + clientHeight >= scrollHeight - 1) {
            // 触发你的函数
            // console.log('handleLoadMoreDialogueTags');
            handleLoadMoreDialogueTags();
        }
    };

    const handleFirstTimeLoadData = async (containerRef) => {
        const thisTimeloadedDataLength = await handleLoadMoreDialogueTags();

        if (!thisTimeloadedDataLength) {
            return
        }
        const { scrollHeight, clientHeight } = containerRef.current;
        // console.log(scrollHeight, clientHeight);
        if (scrollHeight == clientHeight) {
            handleFirstTimeLoadData(containerRef);
        }
    }

    useEffect(() => {
        handleFirstTimeLoadData(containerRef);

        const container = containerRef.current;
        container.addEventListener('scroll', handleScroll);

        // 清理监听器
        return () => {
            container.removeEventListener('scroll', handleScroll);
        };
    }, []);

    // if (isLoading) {
    //     return <CircularProgress size={30} color='inherit' />
    // }

    // if (isLoading) {
    //     return;
    // }

    // if (error) {
    //     return error;
    // }

    return (
        <>
            {dialogueHistoryTags.map((item, index) => {
                return <DialogueHistoryTag item={item} index={index} key={item.uuid} containerRef={containerRef} />
            })}
            {/* {isLoading && <CircularProgress size={16} color='inherit' />} */}
            {error && error}
        </>

    )
};


const Sidebar = memo(({ setSettingsVisibility }) => {
    // console.log('Sidebar');
    const navigate = useNavigate();
    const setCurrentDialogueUUID = useStore(state => state.setCurrentDialogueUUID);

    const isMobileView = useStore(state => state.isMobileView);
    const toggleSidebarVisibility = useStore(state => state.toggleSidebarVisibility);
    const sidebarVisibility = useStore(state => state.sidebarVisibility);

    const handleOnClickNewDialogueButton = () => {
        setCurrentDialogueUUID(null);
        if (isMobileView) toggleSidebarVisibility();
        navigate('/');
    }

    const containerRef = useRef(null);

    return (
        // Sidebar
        <div className='sidebar'
            style={{
                width: isMobileView && '100%',
                position: isMobileView && 'fixed',
                display: !sidebarVisibility && 'none',
            }}>
            <div style={{ display: 'flex', flexDirection: 'column' }} >
                <div className='sidebar-content'>
                    {/* <p>Sidebar</p> */}
                    <div className='button-bar'>
                        <button className='button-bar-button' onClick={toggleSidebarVisibility} ><MenuOpenOutlinedIcon /></button>
                        <button className='button-bar-button' onClick={() => setSettingsVisibility(true)}><TuneOutlinedIcon /></button>
                        <button className='button-bar-button' onClick={handleOnClickNewDialogueButton} ><PostAddOutlinedIcon /></button>
                    </div>

                    <div className='dialogue-history' ref={containerRef}>
                        <DialogueHistoryTags containerRef={containerRef} />
                    </div>
                </div>
            </div>

            {isMobileView && <div className='sidebar-mobile-view-blank' onClick={toggleSidebarVisibility}></div>}
        </div>
    )
});

export default Sidebar;